<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/*数字资源访问记录表model*/

class ResourceTotalAccessNum extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;


    protected $table = 'resource_total_access_num';


    /**
     * 添加所有的访问记录（浏览量）
     * @param resource_guid 资源guid
     * @param resource_business_id 资源商id
     * @param user_id 用户id
     * @param big_type_id 资源大类型id
     * @param type  类型  1 微信公众号 2 微信小程序  3 web
     * @param browse_num  浏览量
     */
    public function addAllAccessNum($resource_guid, $resource_business_id, $big_type_id = null, $user_id = null, $type = 1, $date = null, $browse_num = 1)
    {
        $date = $date ? $date : date('Y-m-d');
        $obj = new self();
        $obj->addAccessNum($resource_guid, $resource_business_id, $big_type_id, $type, $browse_num);
        //数字资源用户访问记录表
        if ($user_id) {
            $resourceTotalAccessNumUser = new ResourceTotalAccessNumUser();
            $resourceTotalAccessNumUser->addAccessNumUser($user_id, $resource_guid, $resource_business_id, $big_type_id, $browse_num);
        }
        //数字资源-资源每天访问次数表
        $resourceTotalAccessNumUserDay = new ResourceTotalAccessNumUserDay();
        $resourceTotalAccessNumUserDay->addAccessNumUserDay($user_id, $resource_guid, $resource_business_id, $big_type_id, $date, $browse_num);
    }

    /**
     * 记录每日浏览量
     * @param resource_guid 资源guid
     * @param resource_business_id 资源商id
     * @param type  类型  1 微信公众号 2 微信小程序  3 web
     *
     * @param browse_num  浏览量
     * @return void
     */
    public function addAccessNum($resource_guid, $resource_business_id, $big_type_id = null, $type = 1, $browse_num = 1)
    {
        $time = time();
        $year = date("Y", $time);
        $month = date("m", $time);
        $day = date("d", $time);

        $browse = $this->where('resource_guid', $resource_guid)->where('resource_business_id', $resource_business_id)->where('yyy', $year)->where('mmm', $month)->where('ddd', $day)->first();

        $type = $type == 1 ? 'wx_num' : ($type == 2 ? 'applet_num' : 'web_num');
        if ($browse) {
            $browse->$type + $browse_num;
            $browse->total_num + $browse_num;
            $browse->save();
        } else {
            $this->resource_guid = $resource_guid;
            $this->resource_business_id = $resource_business_id;
            $this->big_type_id = $big_type_id;
            $this->yyy = $year;
            $this->mmm = $month;
            $this->ddd = $day;
            $this->date = date('Y-m-d');
            $this->$type = 1;
            $this->total_num = $browse_num;
            $this->save();
        }
    }

    /**
     * 访问人数
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     */
    public function getAccessNumber($start_time = null, $end_time = null)
    {
        $number = $this->where(function ($query) use ($start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->sum('total_num');
        return $number;
    }

    /**
     * 单本点击量统计排行榜
     * @param start_time 开始时间 不传，默认是当天
     * @param end_time 结束时间 不传，默认是当天
     * @param big_type_id 系统大类
     * @param resource_business_id  资源商id
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function resourceAccessNumStatistics($resource_business_id, $big_type_id, $start_time, $end_time, $limit)
    {
        $field = ['u.id', 'u.resource_guid', 'u.resource_business_id', 'u.big_type_id', 'r.title', DB::raw("sum(total_num) as access_num")];
        $res = $this->from($this->getTable() . ' as u')->select($field)
            ->join('resource_total as r', 'r.guid', '=', 'u.resource_guid')
            ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where(function ($query) use ($resource_business_id, $big_type_id, $start_time, $end_time) {
                if ($resource_business_id) {
                    $query->where('u.resource_business_id', $resource_business_id);
                }
                if ($big_type_id) {
                    $query->where('u.big_type_id', $big_type_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('u.create_time', [$start_time, $end_time]);
                }
            })->where('r.is_del', 1)
            ->where('n.is_del', 1);

        $total_access_num = $res->sum('total_num');

        $res = $res->groupBy('resource_guid')
            ->orderByDesc('access_num')
            ->orderByDesc('u.create_time')
            ->paginate($limit)
            ->toArray();

        $resourceBusinessNameModel = new ResourceBusinessName();
        $resourceTypeModel = new ResourceType();
        //  $resourceTotalModel = new ResourceTotal();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['resource_business_name'] = $resourceBusinessNameModel->where('id', $val['resource_business_id'])->where('is_del', 1)->value('name');
            $res['data'][$key]['big_type_name'] = $resourceTypeModel->where('id', $val['big_type_id'])->where('is_del', 1)->value('type_name');
            //$res['data'][$key]['title'] = $resourceTotalModel->where('guid', $val['resource_guid'])->where('is_del', 1)->value('title');
        }
        $res['total_access_num'] = $total_access_num;
        return $res;
    }

    /**
     * 资源类型统计排行榜
     * @param start_time 开始时间 不传，默认是当天
     * @param end_time 结束时间 不传，默认是当天
     * @param big_type_id 系统大类
     * @param resource_business_id  资源商id
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function resourceTypeStatistics($resource_business_id, $big_type_id, $start_time, $end_time, $limit)
    {
        $res = $this->from('resource_total_access_num as b')
            ->select('t.type_name', 'at.type_name as big_type_name', 'n.name as resource_business_name', 'b.create_time', DB::raw("sum(total_num) as access_num"))
            ->join('resource_total as r', 'r.guid', '=', 'b.resource_guid')
            ->join('resource_type_external as t', 't.id', '=', 'r.type_id')
            ->join('resource_type as at', 'at.id', '=', 'b.big_type_id')
            ->join('resource_business_name as n', 'n.id', '=', 'b.resource_business_id')
            ->where(function ($query) use ($resource_business_id, $big_type_id) {
                if ($resource_business_id) {
                    $query->where('r.resource_business_id', $resource_business_id);
                }
                if ($big_type_id) {
                    $query->where('r.big_type_id', $big_type_id);
                }
            })
            ->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('b.create_time', [$start_time, $end_time]);
                }
            })
            ->where('r.is_del', 1)
            ->where('n.is_del', 1);

        $total_access_num = $res->sum('total_num'); //计算总数

        $res = $res->groupBy('r.type_id')
            ->orderByDesc('access_num')
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        $res['total_access_num'] = $total_access_num;
        return $res;
    }
    /**
     * 资源类型统计排行榜
     * @param resource_business_id  资源商id
     * @param big_type_id 系统大类
     * @param start_time 开始时间 不传，默认是当天   (时间只对点击量生效)
     * @param end_time 结束时间 不传，默认是当天
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function resourceTotalStatistics($resource_business_id, $big_type_id, $start_time = null, $end_time = null, $limit = 10)
    {
        $res = $this->from('resource_business_name as n')
            ->select('n.name as resource_business_name', 'n.id', 'n.create_time', DB::raw("count(resource_business_id) as resource_num"))
            ->join('resource_total as t', 't.resource_business_id', '=', 'n.id')
            ->where(function ($query) use ($resource_business_id, $big_type_id) {
                if ($resource_business_id) {
                    $query->where('resource_business_id', $resource_business_id);
                }
                if ($big_type_id) {
                    $query->where('big_type_id', $big_type_id);
                }
            })
            ->where('is_mask', 1)
            ->where('n.is_del', 1)
            ->where('t.is_del', 1);

        $total_resource_num = $res->count('resource_business_id'); //计算总数

        $res = $res->groupBy('resource_business_id')
            ->orderByDesc('resource_num')
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['access_num'] = $this->where('resource_business_id', $val['id'])
                ->where(function ($query) use ($big_type_id) {
                    if ($big_type_id) {
                        $query->where('big_type_id', $big_type_id);
                    }
                })->where(function ($query) use ($start_time, $end_time) {
                    if ($start_time && $end_time) {
                        $query->whereBetween('create_time', [$start_time, $end_time]);
                    }
                })
                ->count();
        }

        $resource_business_id_all = ResourceBusinessName::where('is_del', 1)->pluck('id')->toArray();
        $total_access_num = $this->where(function ($query) use ($resource_business_id, $big_type_id) {
            if ($resource_business_id) {
                $query->where('resource_business_id', $resource_business_id);
            }
            if ($big_type_id) {
                $query->where('big_type_id', $big_type_id);
            }
        })->where(function ($query) use ($start_time, $end_time) {
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->whereIn('resource_business_id', $resource_business_id_all)
            ->count();; //计算总数

        $res['total_access_num'] = $total_access_num;
        $res['total_resource_num'] = $total_resource_num;

        return $res;
    }


    /**
     * 资源类型统计排行榜
     * @param resource_business_id  资源商id
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function resourceBigTypeStatistics($resource_business_id, $page = 1, $limit = 10)
    {
        $key = md5('resourceBigTypeStatistics-' . $resource_business_id . '-' . $page . '-' . $limit);
        $res = Cache::get($key);
        if (empty($res)) {
            $res = $this->from('resource_type as n')
                ->select('n.type_name', 'n.id', 'n.create_time', "n.number as resource_num")
                ->join('resource_total as t', 't.big_type_id', '=', 'n.id')
                ->join('resource_business_name as m', 'm.id', '=', 't.resource_business_id')
                ->where(function ($query) use ($resource_business_id) {
                    if ($resource_business_id) {
                        $query->where('resource_business_id', $resource_business_id);
                    }
                })
                ->where('is_mask', 1)
                ->where('t.is_del', 1)
                ->where('m.is_del', 1)
                ->groupBy('big_type_id')
                ->orderByDesc('resource_num')
                ->orderByDesc('create_time')
                ->paginate($limit)
                ->toArray();
            Cache::put($key, $res, 30 * 60);
        }

        $total_resource_num = 0;
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['access_num'] = $this->where('big_type_id', $val['id'])
                ->where(function ($query) use ($resource_business_id) {
                    if ($resource_business_id) {
                        $query->where('resource_business_id', $resource_business_id);
                    }
                })
                ->count();
            $total_resource_num += $val['resource_num']; //计算总数
        }

        $resource_business_id_all = ResourceBusinessName::where('is_del', 1)->pluck('id')->toArray();
        $total_access_num = $this->where(function ($query) use ($resource_business_id) {
            if ($resource_business_id) {
                $query->where('resource_business_id', $resource_business_id);
            }
        })->whereIn('resource_business_id', $resource_business_id_all)
            ->count(); //计算总数

        $res['total_resource_num'] = $total_resource_num;
        $res['total_access_num'] = $total_access_num;

        return $res;
    }


    /**
     * 获取书籍阅读次数排行榜
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param type 以不同时间形式展示数据 year month week day  类型和时间一起上传，默认以类型为准
     * @param resource_business_id 资源商
     * @param big_type_id 系统大类
     * @param limit
     */
    public function getReadAccessRank($start_time = null, $end_time = null, $type = 'year', $resource_business_id = null, $big_type_id = null, $limit = 10)
    {
        if ($big_type_id == 999) {
            return null;
        }
        if ($type == 'year') {
            $start_time = date('Y-01-01');
            $end_time = date('Y-m-d');
        } elseif ($type == 'month') {
            $start_time = date('Y-m-01');
            $end_time = date('Y-m-d');
        } elseif ($type == 'week') {
            $time = ('1' == date('w')) ? strtotime('Monday', time()) : strtotime('last Monday', time()); //获取本周的开始时间戳
            //$start_time = date('Y-m-d', strtotime('-7 day'));
            $start_time = date('Y-m-d', $time);
            $end_time = date('Y-m-d');
        } elseif ($type == 'day') {
            $start_time = date('Y-m-d');
            $end_time = date('Y-m-d');
        }
        $res = $this->from('resource_total_access_num as b')
            ->select('r.id', 'r.guid', 'r.title', 'r.author', 'r.img', 'r.resource_business_id', 'b.create_time', DB::raw("sum(total_num) as access_num"))
            ->join('resource_total as r', 'r.guid', '=', 'b.resource_guid')
            ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where(function ($query) use ($resource_business_id, $big_type_id) {
                if ($resource_business_id) {
                    $query->where('r.resource_business_id', $resource_business_id);
                }
                if ($big_type_id) {
                    $query->where('r.big_type_id', $big_type_id);
                }
            })
            ->where(function ($query) use ($start_time, $end_time) {
                if ($start_time && $end_time) {
                    $query->whereBetween('b.date', [$start_time, $end_time]);
                }
            })->where('r.is_del', 1)
            ->where('is_mask', 1)
            ->where('n.is_del', 1)
            ->groupBy('guid')
            ->orderByDesc('access_num')
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['access_num'] = format_number($val['access_num']);
        }
        return $res;
    }
}
